package kr.zetaomicron.ultrasolitaire;

import java.util.Random;

public class Deck {
	private Card[] mCard;
	private int mCardCount;
	private int mTotalCards;

	public Deck(int decks) {
		Init(decks, 4, 13);
	}

	public Deck(int decks, int suits, int ranks) {
		if (suits == 2) {
			decks *= 2;
		} else if (suits == 1) {
			decks *= 4;
		}
		Init(decks, suits, ranks);
	}

	private void Init(int decks, int suits, int ranks) {
		mCardCount = decks * ranks * suits;
		mTotalCards = mCardCount;
		mCard = new Card[mCardCount];
		for (int deck = 0; deck < decks; deck++) {
			for (int suit = 0; suit < suits; suit++) {
				for (int value = 0; value < ranks; value++) {
					mCard[deck*suits*ranks + suit*ranks + value] = new Card(value+1, suit);
				}
			}
		}

		Shuffle();
		Shuffle();
		Shuffle();
	}

	public void PushCard(Card card) {
		mCard[mCardCount++] = card;
	}

	public Card PopCard() {
		if (mCardCount > 0) {
			return mCard[--mCardCount];
		}
		return null;
	}

	public boolean Empty() {
		return mCardCount == 0;
	}

	public void Shuffle() {
		int lastIdx = mCardCount - 1;
		int swapIdx;
		Card swapCard;
		Random rand = new Random();

		while (lastIdx > 1) {
			swapIdx = rand.nextInt(lastIdx);
			swapCard = mCard[swapIdx];
			mCard[swapIdx] = mCard[lastIdx];
			mCard[lastIdx] = swapCard;
			lastIdx--;
		}
	}
}